package com.example.asset.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;

public class UtilPassword{

    // 生成随机盐
    public static String generateSalt(int length){
        SecureRandom random = new SecureRandom();
        byte[] saltBytes = new byte[length / 2]; // 每个字节转换为两个十六进制字符
        random.nextBytes(saltBytes);
        return bytesToHex(saltBytes);
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes){
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // 将十六进制字符串转换为字节数组
    private static byte[] hexToBytes(String hex){
        byte[] bytes = new byte[hex.length() / 2];
        for(int i = 0; i < bytes.length; i++){
            bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }

    public static boolean verifyPassword(String inputPassword, String storedHash, String storedSalt){
        // 使用存储的盐和哈希算法对用户输入的密码进行哈希
        String inputHash = hashPassword(inputPassword, storedSalt);

        // 将用户输入的哈希与存储的密码哈希进行比较
        return inputHash.equals(storedHash);
    }


    // 使用盐和SHA-256哈希函数加密密码
    public static String hashPassword(String password, String salt){
        try{
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] saltBytes = hexToBytes(salt);
            md.update(saltBytes);
            byte[] passwordBytes = password.getBytes("UTF-8");
            md.update(passwordBytes);
            byte[] hash = md.digest();
            return bytesToHex(hash);
        } catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args){
        String salt = UtilPassword.generateSalt(16);
        System.out.println(salt);
        String s = UtilPassword.hashPassword("123456", salt);
        System.out.println(s);
        System.out.println(UtilPassword.verifyPassword("123456", s, salt));

    }

}